package com.yzy.soft.system.freemarker;

import com.yzy.soft.system.freemarker.JavaFileController;
import com.yzy.soft.system.freemarker.TemplateKernel;
import com.yzy.soft.system.freemarker.FileInfo;
import com.yzy.soft.system.freemarker.database.Table;
import com.yzy.soft.system.freemarker.DBInfo;
import freemarker.template.Template;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class TemplateKernel {

    protected List<File> fileList;


    public List<File> getFileList() {
        return fileList;
    }

    public void setFileList(List<File> fileList) {
        this.fileList = fileList;
    }

    protected File generateFileType(final String templateName) throws Exception {
        return this.generateFileByTemplate(templateName, null, null, null);
    }
    protected File generateFileType(File file) throws Exception {
        return this.generateFileByTemplate(null, file, null, null);
    }
    protected File generateFileType(FileInfo fileInfo) throws Exception {
        return this.generateFileByTemplate(null, null, fileInfo, null);
    }
    protected File generateFileType(FileInfo fileInfo, Table table) throws Exception {
        return this.generateFileByTemplate(null, null, fileInfo, null);
    }
    protected File generateFileType(FileInfo fileInfo,DBInfo dbInfo) throws Exception {
        return this.generateFileByTemplate(null, null, fileInfo, null);
    }
    protected File generateFileType(FileInfo fileInfo, Table table, DBInfo dbInfo) throws Exception {
        return this.generateFileByTemplate(null, null, fileInfo, null);
    }

    protected File generateFileType(final String templateName, File file, FileInfo fileInfo, Map<String, Object> dataMap) throws Exception {
        return this.generateFileByTemplate(templateName, file, fileInfo, dataMap);
    }

    protected File generateFileByTemplate(final String templateName, File file, FileInfo fileInfo, Map<String, Object> dataMap) throws Exception {
        if (file.exists()) {
            file.deleteOnExit();
            file.createNewFile();
        }else{
            file.createNewFile();
        }
        Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
        FileOutputStream fos = new FileOutputStream(file);
//        dataMap.put("author", fileInfo.getAuthor());
        dataMap.put("author", "yinzhiyuan");

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Calendar calendar = Calendar.getInstance();
//        dataMap.put("date", fileInfo.getCreateTime());
        dataMap.put("date", format.format(calendar.getTime()));
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
        template.process(dataMap, out);
        return file;
    }


}
